package br.ucb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.ucb.connection.MyConnection;
import br.ucb.model.Fornecedor;

public class FornecedorDao {
	public void add(Fornecedor fornecedor){
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "INSERT INTO FORNECEDOR VALUES(?,?);";
			st = con.prepareStatement(sql);
			st.setString(1, fornecedor.getCnpj());
			st.setString(2, fornecedor.getNome());
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {	
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	public List<Fornecedor> findAll(){
		Connection con;
		Statement st;
		ResultSet rs;
		String sql;
		List<Fornecedor> fornecedores = new ArrayList<Fornecedor>();
		
		try {
			con = MyConnection.getConnection();
			st = con.createStatement();
			sql = "SELECT * FROM FORNECEDOR;";
			rs = st.executeQuery(sql);
			while(rs.next())
				fornecedores.add(new Fornecedor(rs.getString("NOME"),rs.getString("CNPJ")));
			MyConnection.closeConnection(con, st, rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
		return fornecedores;		
	}
	public void update(Fornecedor fornecedor){
		Connection con;
		PreparedStatement st;
		String sql="";
		try{
			con = MyConnection.getConnection();
			sql = "UPDATE FORNECEDOR SET NOME=?;";
			st = con.prepareStatement(sql);
			st.setString(1, fornecedor.getNome());
			st.execute();
			MyConnection.closeConnection(con, st);
		}catch(SQLException e){
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	public void delete(Fornecedor fornecedor){
		Connection con;
		PreparedStatement st;
		String sql="";
		try {
			con = MyConnection.getConnection();
			sql = "DELETE FROM FORNECEDOR WHERE CNPJ=?;";
			st = con.prepareStatement(sql);
			st.setString(1, fornecedor.getCnpj());
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
